from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from constr_budgets.models import Place, Project
import json


# Create your place here.

class PlaceView(View):
    def get(self, request):
        tem_id = request.GET.get('template_id')  # 获取模板idy
        aimlist = Place.objects.filter(template_id=tem_id).values()
        add = 0
        for ai in aimlist:
            add += ai['square']
        print(tem_id)
        print(aimlist)
        return JsonResponse({
            "code": 200,
            "message": "获取动态数据成功",
            "count": add,
            "data": list(aimlist)
        })

    def post(self, request):
        # name square template
        data = json.loads(request.body)  # 获取前端返回数据
        try:
            # project = Project.objects.filter(id=data['project_id']).values()  # 根据返回的项目id 查找模板id
            Place.objects.create(name=data['name'], square=data['square'], template_id=data['models_id'])
        except:
            return JsonResponse({"code": 403, "message": "参数类型错误"})
        return JsonResponse({"code": 200, "message": "添加成功"})

    def put(self, request):
        data = json.loads(request.body)
        id = data['id']
        data.pop("id")
        Place.objects.filter(id=id).update(**data)
        return JsonResponse({"code": 200, "message": "修改成功"})

    def delete(self, req):
        id = req.GET.get("id")
        Place.objects.get(id=id).delete()
        return JsonResponse({"code": 200, "message": "删除成功"})
